<?php

namespace addons\order\user\controller;

/**
 * 提现
 */
class WageWithoutOrder extends \web\user\controller\AddonUserBase {

    public function index() {
        $status = $this->_get('status');
        if ($status == '') {
            $status = 0;
        }
        $this->assign('status', $status);
        return $this->fetch();
    }

    public function loadList() {
        $keyword = $this->_get('keyword');
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        $status = $this->_get('status');
        $filter = 'status=' . $status;
        if ($keyword != null) {
            $filter .= ' and (b.username like \'%' . $keyword . '%\' or b.phone  like \'%' . $keyword . '%\')';
        }
        if ($startDate != null && $endDate != null)
            $filter .= ' and (a.add_time >= \'' . $startDate . ' 00:00:00\' and a.add_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (a.add_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (a.add_time <= \'' . $endDate . ' 23:59:59\')';
        $r = new \addons\order\model\Without();
        $total = $r->getWithoutTotal($filter);
        $count_total = $r->getWithoutSum($filter);
        $fields = 'a.*,b.username,b.phone,d.name as balance_name';
        $rows = $r->getWithoutList($this->getPageIndex(), $this->getPageSize(), $filter, $fields, 'id desc');
        return $this->toTotalDataGrid($total, $rows,$count_total);
    }


    public function doCheckMore(){
        $str = trim($this->_get('id'),','); //提现订单id
        $str = str_replace('undefined', '', $str);
        $list = array_filter(explode(',', $str));
        $state = 1;
        $withoutM = new \addons\order\model\Without();
        $balanceM = new \addons\member\model\Balance();
        $recordM = new \addons\member\model\TradingRecord();
        try {
            foreach ($list as $key => $orderId) {
                $orderData = $withoutM->getDetail($orderId);
                //获取用户奖金信息
                $balanceM->startTrans();
                $res = (new \addons\member\model\DailyBonus)->addBonus($orderData['rate'],1);
                if(!$res){
                    $balanceM->rollback();
                    return $this->failData('添加奖金池失败');
                }
                //修改订单状态
                $without_update = $withoutM->where(['id' => $orderId])->update(['status' => $state, 'update_time' => NOW_DATETIME]);
                if(!$without_update){
                    $balanceM->rollback();
                    return $this->failData('修改提现状态失败');
                }
                $this->addLog(self::LOG_EDIT,'提现订单审核通过',$_GET, $orderData['user_id']);
                $balanceM->commit();
            }
            return $this->successData();
        } catch (\Exception $ex) {
            $balanceM->rollback();
            return $this->failData($ex->getMessage());
        }
    }
    
    //审核
    public function doCheck() {
        $orderId = $this->_get('id'); //提现订单id
        $state = $this->_get('status');
        $withoutM = new \addons\order\model\Without();
        $balanceM = new \addons\member\model\Balance();
        $recordM = new \addons\member\model\TradingRecord();
        $orderData = $withoutM->getDetail($orderId);
        try {
            //获取用户奖金信息
            $balanceM->startTrans();
            if ($state == -1) {
                //返回提现金额
                $re_balance = $balanceM->updateBalance($orderData['user_id'], $orderData['coin_type'], $orderData['amount'], true);
                if(!$re_balance){
                    $balanceM->rollback();
                    return $this->failData('提现订单退回金额失败');
                }

                //写入交易记录
                $re_record = $recordM->addRecord($orderData['user_id'], $orderData['amount'], $re_balance['before_amount'], $re_balance['amount'], $orderData['coin_type'], 2, 1, 0, '驳回提现金额,订单号为：'.$orderData['ref_no']);
                if(!$re_record){
                    $balanceM->rollback();
                    return $this->failData('提现订单退回金额流水失败');
                }

                //手续费
                $re_balance = $balanceM->updateBalance($orderData['user_id'], $orderData['coin_type'], $orderData['rate'], true);
                if(!$re_balance){
                    $balanceM->rollback();
                    return $this->failData('提现订单退回手续费失败');
                }

                //写入交易记录
                $re_record = $recordM->addRecord($orderData['user_id'], $orderData['rate'], $re_balance['before_amount'], $re_balance['amount'], $orderData['coin_type'], 2, 1, 0, '驳回提现手续费,订单号为：'.$orderData['ref_no']);
                if(!$re_record){
                    $balanceM->rollback();
                    return $this->failData('提现订单退回手续费流水失败');
                }

                //返回提现金额
                $re_balance = $balanceM->updateBalance($orderData['user_id'], 4, $orderData['gx_amount'], true);
                if(!$re_balance){
                    $balanceM->rollback();
                    return $this->failData('提现订单退回贡献值失败');
                }

                //写入交易记录
                $re_record = $recordM->addRecord($orderData['user_id'], $orderData['gx_amount'], $re_balance['before_amount'], $re_balance['amount'], 4, 2, 1, 0, '驳回提现贡献值,订单号为：'.$orderData['ref_no']);

                if(!$re_record){
                    $balanceM->rollback();
                    return $this->failData('提现订单退回贡献值流水失败');
                }

                //修改订单状态
                $without_update = $withoutM->where(['id' => $orderId])->update(['status' => $state, 'update_time' => NOW_DATETIME]);
                if(!$without_update){
                    $balanceM->rollback();
                    return $this->failData('修改订单状态失败');
                }
                //添加管理日志
                $this->addLog(self::LOG_EDIT,'提现订单审核驳回',$_GET, $orderData['user_id']);
            }else{

                $accountM = new \addons\member\model\MemberAccountModel();
                $levelConfigM = new \addons\member\model\LevelConfig();
                //手续费分红
                $level_list = $levelConfigM->where(['commission_bonus_rate' => ['>', '0']])->order('level asc')->select();
                if($level_list){
                    $rewardForLogM = new \addons\member\model\RewardForLog();
                    foreach ($level_list as $value){
                        $user_id_list = $accountM->where(['level' => $value['level'], 'is_frozen' => 0, 'is_auth' => 1, 'logic_delete' => 0])->column('id');
                        if($user_id_list){
                            $user_count = count($user_id_list);
                            //获取当前等级的平均金额
                            $divide_amount = round((($orderData['rate'] * $value['commission_bonus_rate'] / 100 ) / $user_count), 2);
                            if($divide_amount > 0){
                                foreach ($user_id_list as $val){
                                    //放入记录
                                    $rewardForLogM->addRecord($val, $orderData['user_id'], 3, 102, $divide_amount, '手续费分红');
                                }
                            }
                        }
                    }
                }
                //修改订单状态
                $without_update = $withoutM->where(['id' => $orderId])->update(['status' => $state, 'update_time' => NOW_DATETIME]);
                if(!$without_update){
                    $balanceM->rollback();
                    return $this->failData('修改提现状态失败');
                }
                $this->addLog(self::LOG_EDIT,'提现订单审核通过',$_GET, $orderData['user_id']);
            }
            $balanceM->commit();
            return $this->successData();
        } catch (\Exception $ex) {
            $balanceM->rollback();
            return $this->failData($ex->getMessage());
        }
    }


    //导出
    public function export(){
        ob_end_clean();
        $keyword = $this->_get('keyword');
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        $status = $this->_get('status');
        $filter = 'status=' . $status;
        if ($keyword != null) {
            $filter .= ' and (b.username like \'%' . $keyword . '%\' or b.phone  like \'%' . $keyword . '%\')';
        }
        if ($startDate != null && $endDate != null)
            $filter .= ' and (a.add_time >= \'' . $startDate . ' 00:00:00\' and a.add_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (a.add_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (a.add_time <= \'' . $endDate . ' 23:59:59\')';
        $r = new \addons\order\model\Without();
        $total = $r->getWithoutTotal($filter);
        $fields = 'a.*,b.username,b.phone,d.name as balance_name';
        $rows = $r->getWithoutList($this->getPageIndex(), $this->getPageSize(), $filter, $fields, 'id desc');
        $fileName = '提现记录_'.NOW_DATETIME.'.csv';
        header('Content-type: text/html;charset=utf-8');
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        $header = [
            ['title' => '编号', 'field' => 'id'],
            ['title' => '用户ID', 'field'=> 'user_id'],
            ['title' => '手机号', 'field'=> 'phone'],
            ['title' => '提现单号', 'field'=> 'ref_no'],
            ['title' => '提现数量', 'field' => 'amount'],
            ['title' => '提现手续费', 'field'=> 'rate'],
            ['title' => '提现类型', 'field'=> 'balance_name'],
            ['title' => '提现时间', 'field'=> 'add_time'],
        ];

//         将数据通过fputcsv写到文件句柄
//         CSV的Excel支持GBK编码，一定要转换，否则乱码
        $head = [];
        foreach($header as $val){
            $head[] = iconv('utf-8', 'gbk', $val['title']);
        }
        fputcsv($fp, $head);
        $i = 0;
        // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;
        $data = [];
        foreach ($rows as &$row) {
            if ($limit == $i) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $i = 0;
            }
            $arr = [];
            foreach ($header as $key => $val) {
                $value = isset($row[$val['field']]) ? $row[$val['field']] : "";
                $arr[$val['field']] = iconv('utf-8', 'gbk//IGNORE', $value."\t");
            }
            fputcsv($fp, $arr);
        }
    }

}
